package com.yupi.yuojbackendjudgeservice.judege.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import com.yupi.yuojbackendcommon.common.ErrorCode;
import com.yupi.yuojbackendcommon.exception.BusinessException;
import com.yupi.yuojbackendjudgeservice.judege.codesandbox.CodeSandbox;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import yuojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import yuojbackendmodel.model.codesandbox.ExecuteCodeResponse;

/**
 * @Description 远程代码沙箱（实际调用）
 * @Author JFeng
 * @Date 2023/10/14
 */
@Service
public class RemoteCodeSandboxImpl implements CodeSandbox {
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Value("${codesandbox.ip}")
    private String codeSandboxIp;

    @Value("${codesandbox.port}")
    private String codeSandboxPort;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String url = "http://localhost:8090/executeCode";
        String url1 = "http://" + codeSandboxIp + ":" + codeSandboxPort + "/executeCode";
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET)
                .body(JSONUtil.toJsonStr(executeCodeRequest))
                .execute()
                .body();
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remote error, message = {" + responseStr + "}");
        }
        ExecuteCodeResponse response = JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
        return response;
    }
}
